from datetime import datetime, timedelta
from flask import current_app
import jwt
from ..models.user import User
from .. import db

class AuthService:
    @staticmethod
    def create_user(username, email, password):
        """创建新用户"""
        user = User(username=username, email=email)
        user.set_password(password)
        user.save()
        return user
    
    @staticmethod
    def authenticate_user(username, password):
        """验证用户凭据"""
        user = User.query.filter_by(username=username).first()
        if user and user.check_password(password):
            return user
        return None
    
    @staticmethod
    def generate_token(user):
        """生成JWT令牌"""
        payload = {
            'user_id': user.id,
            'exp': datetime.utcnow() + timedelta(days=1)
        }
        return jwt.encode(
            payload,
            current_app.config['SECRET_KEY'],
            algorithm='HS256'
        )
    
    @staticmethod
    def verify_token(token):
        """验证JWT令牌"""
        try:
            payload = jwt.decode(
                token,
                current_app.config['SECRET_KEY'],
                algorithms=['HS256']
            )
            user = User.query.get(payload['user_id'])
            return user
        except jwt.ExpiredSignatureError:
            return None
        except jwt.InvalidTokenError:
            return None